package com.shiro.Controller;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Security;

@Controller
public class UserController {
    //{url}是一个占位符，表示这部分URL是动态的，可以在方法参数中通过 @PathVariable获取。
    //通过thymeleaf去自动寻找url
    @RequestMapping("/{url}")
    public String redirect(@PathVariable("url") String url) {
        return url;
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model) {
        Subject subject= SecurityUtils.getSubject();
        System.out.println(subject);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);//调用这个方法后,会自动进到我们自己写的realm中
            return "index";
        }
        catch (AuthenticationException e) {
            e.printStackTrace();
            //Model类似于一个键值对（Map），可以存储需要在页面上显示的数据。
            model.addAttribute("error", "该用户无权限");
            return "login";
        }

    }
    @RequestMapping("/unauthorized")
    public String unauthorized(){
        return "unauthorized";
    }

    @RequestMapping("/loginOut")
    public String loginOut() {
        SecurityUtils.getSubject().logout();
        return "login";
    }
}
